package 分治;

/**
 * @description:
 * @author: ywk 数组Shuffle
 * @date: 2021-03-02
 */
public class 数组Shuffle {
    public static void main(String[] args) {
        int[] arr = {1, 2, 5, 7, 3, 1, 6, 8};
        CommonUtil.printArr(arr);
        divideArr(arr, 0, arr.length - 1);
        maxIndexDiff(arr);
    }

    //a1a2a3a4a5 b1b2b3b4b5
    //a1b2a2b2a3 b3a4b4a5b5
    public static void ShuffleArray(int[] arr) {
        int n = arr.length / 2;
        for (int i = 0; i < n; i++) {
            int index = i * 2;
            int temp = arr[index + (n - i)];
            int targetIndex = index + (n - i);
            for (int j = targetIndex; j > index + 1; j--) {
                arr[j] = arr[j - 1];
            }
            arr[index + 1] = temp;
        }
    }

    //通过分治法
    public static void divideArr(int[] arr, int left, int right) {
        if (left + 3 <= right) {
            int gap = (right - left + 1) / 4;
            int mid = left + (right - left) / 2;
            int index = left + gap;
            int temp = index;
            while (index < temp + gap) {
                CommonUtil.swap(arr, index, index + gap);
                index++;
            }
            CommonUtil.printArr(arr);
            divideArr(arr, left, mid);
            divideArr(arr, mid + 1, right);
        }
    }

    public static int maxIndexDiff(int[] arr) {
        int[] leftMins = new int[arr.length];
        int[] rightMaxs = new int[arr.length];
        leftMins[0] = arr[0];
        for (int i = 1; i < arr.length; i++) {
            leftMins[i] = Math.min(arr[i], arr[i - 1]);
        }
        rightMaxs[arr.length - 1] = arr[arr.length - 1];
        for (int i = arr.length - 2; i >= 0; i--) {
            rightMaxs[i] = Math.max(arr[i], arr[i + 1]);
        }
        int i = 0, j = 0, maxDiff = -1;
        while (j < arr.length && i < arr.length) {
            if (leftMins[i] < rightMaxs[j]) {
                maxDiff = Math.max(maxDiff, j - i);
                j++;
            } else {
                i++;
            }
        }
        System.out.println(maxDiff);
        return maxDiff;
    }
}
